#include<iostream>
#include<cmath>
#define LL long long
using namespace std;

int gcd(int a,int b)
{
	return b==0?a:gcd(b,a%b);
}

int main()
{
	int n,m;
	while(cin>>m>>n&&n!=0)
	{
		LL sum=0;
		for(int i=1;i<=n;i++)
		{
			int tmp=gcd(n,i);
			sum+=(LL)pow(m*1.0,tmp);
		}
		if(n&1)
			sum+=(LL)(n*pow(m*1.0,(n+1)/2));
		else
		{
			sum+=(LL)((n/2)*pow(m*1.0,(n+2)/2));
			sum+=(LL)((n/2)*pow(m*1.0,n/2));
		}
		sum=sum/(2*n);
		cout<<sum<<endl;
	}
	return 0;
}


